<?php
	header('Content-Type: application/json');
	header('Access-Control-Allow-Origin: *');

	include_once('../connect2db.php');
	
	if ($_SERVER['REQUEST_METHOD'] === 'GET') {
		switch ($_REQUEST['v1']) {
			case 'getPlotData':
				$returnObject = getPlotData(@$_GET['range']);

				break;
			default:
				$returnObject = (object) array(
					"error_code" => 2000,
					"error_msg" => "未知的api接口",
				);
		}

		echo json_encode($returnObject);
	} else if ($_SERVER['REQUEST_METHOD'] === 'POST') {
		switch ($_REQUEST['v1']) {
			case 'update':
				$returnObject = update(@$_POST['temp1'], @$_POST['temp2']);

				break;
			default:
				$returnObject = (object) array(
					"error_code" => 2000,
					"error_msg" => "未知的api接口",
				);
		}

		echo json_encode($returnObject);
	}

	function getPlotData($range) {
		if (!$range) {$range = 1;}

		$returnObject = array();

		$result = mysql_query(
								"SELECT " .
									"recorders.temperature1," .
									"recorders.temperature2," .
									"recorders.`timestamp`" .
								" FROM " .
									"temperature_recorders AS recorders" .
								" WHERE " .
									"recorders.`timestamp` > DATE_SUB(NOW(), INTERVAL $range HOUR)"
							);

		//$count = 0;

		$record_lists;
		
		while ($row = mysql_fetch_assoc($result)) {
			$list = array(
				$row['timestamp'],
				$row['temperature1'],
				$row['temperature2']
			);

			$record_lists[] = array("value" => $list);
		}

		$returnObject = array(
			"result" => "success",
			"data" => $record_lists
		);
		
		return $returnObject;
	}
	
	function update($temp1, $temp2) {		
		$returnObject = array();
		
		if (!$temp1 || empty($temp1)) {
			$returnObject = (object) array(
				"error_code" => 1000,
				"error_msg" => "参数错误：temperature1 不能为空！"
			);

			return $returnObject;
		}

		if (!$temp2 || empty($temp2)) {
			$returnObject = (object) array(
				"error_code" => 1001,
				"error_msg" => "参数错误：temperature2 不能为空！"
			);

			return $returnObject;
		}
		
		mysql_query("insert into `temperature_recorders` (temperature1, temperature2, timestamp) values ('$temp1', '$temp2', NOW())");

		if (mysql_error() !== "") {
			$returnObject = (object) array(
				"error_code" => 2001,
				"error_msg" => mysql_error()
			);

			return $returnObject;
		}
		
		$returnObject = array(
			"result" => "success"
		);

	    return $returnObject;
	}
?>